<template>
    <div>
        <div class="content">
            <el-button type="primary" size="mini" @click="handleButton('primary-search')">查询</el-button>
            <el-button type="primary" size="mini" @click="handleButton('refresh')"> 刷新</el-button>
            <el-button type="primary" size="mini" @click="handleButton('check-pass')">复核通过</el-button>
            <el-button type="danger" size="mini" @click="handleButton('check-refuse')">复核拒绝</el-button>
            <el-button type="primary" size="mini" @click="handleButton('doLayout')" style="float:right"> 布局设置</el-button>
        </div>

        <div class="noOpened">
            <RiskTableP
                :ref="'risk-table'"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="showColumns"
                :paging="paging"
                v-loading="tableLoading"
                @page-change="getTableData"
                :key="tableKey"
                :checkMethod="checkMethod"
            >
                <template #operation="{ row }">
                    <RiskIconButton type="primary" icon="el-icon-view" topTitle="查看" @on-click="handleBtnRow('look', row)"></RiskIconButton>
                    <RiskIconButton
                        type="primary"
                        icon="el-icon-circle-check"
                        topTitle="复核通过"
                        :disabled="row.modifyStatus != '1'"
                        @on-click="handleBtnRow('check-pass', row)"
                    ></RiskIconButton>
                    <RiskIconButton
                        type="danger"
                        icon="el-icon-circle-close"
                        topTitle="复核拒绝"
                        :disabled="row.modifyStatus != '1'"
                        @on-click="handleBtnRow('check-refuse', row)"
                    ></RiskIconButton>
                </template>
            </RiskTableP>
        </div>
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="layoutTableName"
            :visible.sync="layoutDialog"
            :column="tableColumns"
            :fixedColumns="fixedColumns"
        />

        <!-- 高级查询 -->
        <StrategyCheckPrimarySearch
            :searchParam="searchParam"
            :visible.sync="primarySearchVisible"
            @handleButton="handleButton($event.type, $event.params)"
        ></StrategyCheckPrimarySearch>

        <!-- 复核弹框 -->
        <yh-dialog
            :title="verificationTitle"
            :visible.sync="verificationVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="600px"
            drag
        >
            <div style="overflow: auto">
                <!-- 仅用于显示即可 -->
                <ComparionRecord :checkedRowKeys="checkedRowKeys" :title="'密码策略'"></ComparionRecord>
                <div>
                    <p style="font-size: 15px; padding-bottom: 5px">【备注原因】</p>
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请备注原因" v-model="checkReason"> </el-input>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="verificationVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleButton('verificate-confirm')">确 定 </el-button>
            </div>
        </yh-dialog>

        <!-- 查看弹框 -->
        <yh-dialog title="复核查看" :visible.sync="lookVisible" width="1100px" :close-on-click-modal="false" :close-on-press-escape="false" drag>
            <!-- <div class="user-list-dialog">
                <el-form ref="form" :model="lookInfo" label-width="145px" size="mini">
                    <el-form-item label="序号">
                        <el-input placeholder="自动生成" size="mini" disabled v-model="lookInfo.strategyCode" class="list-dialog-form"></el-input>
                    </el-form-item>
                    <el-form-item label="复核状态">
                        <el-select size="mini" class="list-dialog-form" v-model="lookInfo.modifyStatus" disabled>
                            <el-option v-for="(value, key) in Dict.modifyStatusPojo" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="事件">
                        <el-select size="mini" class="list-dialog-form" v-model="lookInfo.eventType" disabled>
                            <el-option v-for="(value, key) in Dict.eventTypePojo" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div> -->
            <StrategyForm :initForm="initForm" ref="strategy-form" type="look"></StrategyForm>
            <el-divider></el-divider>
            <ComparionRecord :checkedRowKeys="checkedRowKeys" title="密码策略"></ComparionRecord>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" type="danger" @click="handleButton('look-check-refuse')">复核拒绝</el-button>
                <el-button size="mini" type="primary" @click="handleButton('look-check-pass')">复核通过</el-button>
                <el-button size="mini" @click="lookVisible = false">取 消</el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { dateFormat, getCurrentPageData, timeFormat } from '@/utils/tools';
import API from '../api/password-strategy';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import Dict from '../dict/password-strategy';
import DictionConstUtil from '@/utils/diction-const-util';
import ComparionRecord from '../auth-manage/comparion-record.vue';
import { StrategyCheckDTO, StrategySettingDTO } from '../vo/password-strategy';
import StrategyCheckPrimarySearch from './strategy-check-primary-search.vue';
import StrategyForm from './strategy-form.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'StrategyCheck',
    components: {
        RiskIconButton,
        RiskTableLayout,
        RiskTableP,
        ComparionRecord,
        StrategyCheckPrimarySearch,
        StrategyForm,
    },
})
export default class StrategyCheck extends Vue {
    @Prop() activeValue: string;
    // 字典
    Dict = new Dict();
    // 个性化
    verificationVisible: boolean = false;
    verificationTitle: string = ''; // 复核弹框title
    checkReason: string = ''; // 复核原因
    curType: string = ''; // 点击类型
    lookVisible: boolean = false; // 查看弹框
    lookInfo: any = {}; // 密码策略基本信息
    lookRole: any = []; // 已选密码策略

    tableData: any[] = [];

    tableColumns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        { field: 'strategyCode', title: '序号', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'modifyStatus',
            title: '复核状态',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList2(this.Dict.modifyStatusPojo),
            render: value => this.Dict.modifyStatusPojo[value],
        }, // 待复核、复核通过、复核拒绝
        {
            field: 'eventType',
            title: '事件',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList2(this.Dict.eventTypePojo),
            render: value => this.Dict.eventTypePojo[value],
        },
        { field: 'checkUser', title: '复核人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'checkDate',
            title: '复核时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.checkTime)).trim(),
        },
        { field: 'creator', title: '创建人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'createDate',
            title: '创建时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.createTime)).trim(),
        },
        { field: 'modifyUser', title: '更新人', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'modifyDate',
            title: '更新时间',
            align: 'center',
            sortable: true,
            minWidth: '180px',
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.modifyTime)).trim(),
        },
        { field: 'operation', fixed: 'right', title: '操作', align: 'center', width: '150px' },
    ];

    tableConfig: TableConfigVO = {
        rowKey: 'strategyCode',
    };

    fixedColumns: any[] = [
        { field: 'strategyCode', title: '序号', sortable: true, minWidth: '120px', filterType: 'search', filters: [{ data: '' }] },
        {
            field: 'modifyStatus',
            title: '复核状态',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList2(this.Dict.modifyStatusPojo),
            render: value => this.Dict.modifyStatusPojo[value],
        }, // 待复核、复核通过、复核拒绝
        {
            field: 'eventType',
            title: '事件',
            align: 'center',
            sortable: true,
            minWidth: '120px',
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList2(this.Dict.eventTypePojo),
            render: value => this.Dict.eventTypePojo[value],
        },
        { field: 'operation', fixed: 'right', title: '操作', align: 'center', width: '150px' },
    ];

    layoutTableName: string = 'TN_Strategy_CHECK';

    requestTableMethodName: any = API.strategyCheckList;

    primarySearchVisible: boolean = false;

    currentRow: any = {}; // 当前行
    visible: boolean = false; // 详情弹框

    searchParam: StrategyCheckDTO = {
        strategyCode: '',
        modifyStatus: [],
        eventType: [],
    };

    layoutDialog: boolean = false; // 布局显示值

    selectedFieldList: any[] = []; // 已选字段

    showColumns: any[] = []; // 展示字段

    tableKey: number = -1; // 表格渲染key

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    tableLoading: boolean = false;

    checkedRowKeys: any = []; // 勾选项keys

    isFirst: boolean = true;
    initForm: StrategySettingDTO = {
        pwdStrategyIsOpen: true,
        pwdRequirements: true,
        pwdStrategyModifyInterval: 0,
        pwdStrategyUserWarnDay: 0,
        firstLockCount: 10,
        firstLockTime: 30,
        firstLockUnit: 'minute',
        secondLockCount: 0,
        secondLockTime: 0,
        secondLockUnit: 'hour',
        thirdLockCount: 0,
        passwordRemCount: 0,
        loginTimeout: 0,
        loginTimeoutUnit: 'minute',
    };
    async mounted() {
        // 监听布局设置
        this.watchShowColumns();

        this.getTableData();
    }

    watchShowColumns() {
        this.$watch(
            () => {
                return (this.$refs['risk-table-layout'] as VueObject).showColumns;
            },
            val => {
                this.showColumns = val && val.length ? val : this.tableColumns;
                this.tableKey++;
            }
        );
    }

    /**
     * 表格数据
     */
    getTableData() {
        this.tableLoading = true;
        return new Promise((resolve, reject) => {
            // this.requestTableMethodName({
            //     ...this.searchParam,
            //     paging: this.paging,
            // })
            //     .then((res: any) => {
            //         this.tableData = res.list || [];
            //         this.paging.total = res.total;
            //         this.tableLoading = false;
            //         resolve(res);
            //     })
            //     .catch(err => {
            //         this.tableLoading = false;
            //         reject(err);
            //     });
            this.$axios
                .get('/role/query/all')
                .then((res: any) => {
                    this.tableData = getCurrentPageData(res, this.paging.currentPage, this.paging.pageSize);
                    this.paging.total = res.length;
                    this.tableLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.tableLoading = false;
                    reject(err);
                });
        });
    }

    /**
     * 查询条件回调
     */
    comReturn(obj) {
        this.searchParam = obj?.searchParam;
    }

    /**
     * 筛选分页
     */
    pageRet() {
        this.getTableData();
    }

    /**
     * 操作行
     */
    async handleButton(type: string, data?: any) {
        if (type == 'primary-search') {
            this.primarySearchVisible = true;
        } else if (type == 'primary-search-confirm') {
            this.primarySearchVisible = false;
            this.searchParam = JSON.parse(JSON.stringify(data));
            this.paging.currentPage = 1;
            await this.getTableData();
        } else if (type == 'primary-search-cancel') {
            this.primarySearchVisible = false;
            // 点击取消或者X掉时恢复默认值
        } else if (type == 'refresh') {
            await this.getTableData();
            this.yh_message_success('刷新成功！');
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        } else if (type == 'check-pass' || type == 'check-refuse') {
            this.curType = type;
            let name = '复核拒绝';
            if (type == 'check-pass') {
                name = '复核通过';
            }
            const checkRowKeys = (this.$refs['risk-table'] as VueObject).checkRowKeys;
            if (checkRowKeys.length < 1) {
                this.yh_message_info(`请先勾选需${name}的数据！`);
                return;
            }
            this.checkedRowKeys = checkRowKeys;
            this.handleVerificationInfo(type);
        } else if (type == 'verificate-confirm') {
            let name = '';
            let requestName;

            if (this.curType == 'check-pass') {
                name = '复核通过';
                requestName = API.checkPass;
            } else if (this.curType == 'check-refuse') {
                name = '复核拒绝';
                requestName = API.checkRefuse;
            }
            // 备注原因是否可为空
            requestName({ strategyCodes: this.checkedRowKeys, checkReason: this.checkReason })
                .then(() => {
                    this.yh_message_success(name + '成功！');
                    this.paging.currentPage = 1;
                    this.getTableData();
                    this.verificationVisible = false;
                    // 清除导出时列表勾选项
                    this.$nextTick(() => {
                        (this.$refs['risk-table'] as any).resetCheckRowKeys();
                    });
                })
                .catch(() => {});
        } else if (type == 'look-check-pass' || type == 'look-check-refuse') {
            this.lookVisible = false;
            this.curType = 'check-pass';
            if (type == 'look-check-refuse') {
                this.curType = 'check-refuse';
            }
            this.handleVerificationInfo(this.curType);
        }
    }

    // 查看行
    handleBtnRow(type: string, row: any) {
        this.curType = type;
        if (type == 'look') {
            this.checkedRowKeys = [row.strategyCode];
            this.lookVisible = true;
            // 获取数据信息
            console.log(row, 'row==================');
            this.lookInfo = JSON.parse(JSON.stringify(row));
            // TODO 请求接口获取更多配置信息展示
        } else if (type == 'check-pass' || type == 'check-refuse') {
            this.checkedRowKeys = [row.strategyCode];
            this.handleVerificationInfo(type);
        }
    }

    /**
     * 复核比对信息显示处理
     */
    handleVerificationInfo(type: string) {
        this.checkReason = '';
        this.verificationVisible = true;
        if (type === 'check-pass') {
            this.verificationTitle = '确定复核通过以下密码策略吗？';
        } else if (type === 'check-refuse') {
            this.verificationTitle = '确定复核拒绝以下密码策略吗？';
        }
    }

    /**
     * 复选框是否可勾选
     */
    checkMethod({ row }) {
        //  TODO key值
        return row.modifyStatus == '1';
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 5px;
    border: 1px solid #f2f2f2;
    margin-bottom: 10px;
}
.noOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 190px) !important;
    }
}
.user-list-dialog {
    & /deep/ .el-form-item__label::after {
        color: red;
    }

    .list-dialog-form {
        width: 240px;
    }
}
</style>
